package handler

import (
	modbus "github.com/thinkgos/gomodbus"
	"github.com/thinkgos/gomodbus/mb"
	"meinong/hardware/global"
	"time"
	"fmt"
)

type RedisKey struct {
	LockName       string
	QueueName      string
	StatisticsName string
}
func Location(Address string, p *modbus.RTUClientProvider, isHead bool) {
	var KeyTable RedisKey
	fmt.Println("====read======")
	if isHead {
		KeyTable = RedisKey{
			LockName:       "HeadLock",
			QueueName:      "HeadRfidList",
			StatisticsName: "Headstatistics",
		}
	} else {
		KeyTable = RedisKey{
			LockName:       "TailLock",
			QueueName:      "TailRfidList",
			StatisticsName: "Tailstatistics",
		}
	}
	fmt.Println("====key======", KeyTable)
	go Calculator(Address, p, KeyTable)
	go GetNowRFID(KeyTable)
}
func LocationV2( isHead bool) {
	var KeyTable RedisKey
	fmt.Println("====read======")
	if isHead {
		KeyTable = RedisKey{
			LockName:       "HeadLock",
			QueueName:      "HeadRfidList",
			StatisticsName: "Headstatistics",
		}
	} else {
		KeyTable = RedisKey{
			LockName:       "TailLock",
			QueueName:      "TailRfidList",
			StatisticsName: "Tailstatistics",
		}
	}
	fmt.Println("====key======", KeyTable)
	go CalculatorV2(isHead, KeyTable)
	go GetNowRFID(KeyTable)
}
//计算器
func Calculator(Address string, p *modbus.RTUClientProvider, KeyTable RedisKey) {

	p.Address = Address

	p.BaudRate = 9600

	p.DataBits = 8

	p.Parity = "N"

	p.StopBits = 1

	p.Timeout = 100 * time.Millisecond

	client := mb.NewClient(p)

	client.LogMode(false)

	err := client.Start()

	if err != nil {
		panic(err)
	}

	redisClient := global.GlobalRedi.Get()
	defer redisClient.Close()
	for {

		value, err := client.ReadHoldingRegisters(1, 0, 1)

		if err != nil {
			fmt.Println("readHoldErr,", err)
		} else {
			for _, v := range value {
				lock_name, err := redisClient.Do("Get", KeyTable.LockName)
				if err != nil {
					fmt.Println(err.Error())
				}

				if lock_name != nil {
					_, err = redisClient.Do("hset", KeyTable.StatisticsName, fmt.Sprintf("%s", lock_name),
						v)
					if err != nil {
						panic(err)
					}

				}
			}
		}
	}
}
func CalculatorV2(  isHead bool,KeyTable RedisKey) {

	client:=global.ModbusClientTail
	if isHead{
		client=global.ModbusClientHead
	}

	redisClient := global.GlobalRedi.Get()
	defer redisClient.Close()
	for {
		value, err := client.ReadHoldingRegisters(1, 0, 1)

		if err != nil {
			fmt.Println("readHoldErr,", err)
		} else {
			for _, v := range value {
				fmt.Println( fmt.Sprintf("%d", v))
				lock_name, err := redisClient.Do("Get", KeyTable.LockName)
				if err != nil {
					fmt.Println(err.Error())
				}

				if lock_name != nil {
					_, err = redisClient.Do("hset", KeyTable.StatisticsName, fmt.Sprintf("%s", lock_name),
						v)
					if err != nil {
						panic(err)
					}

				}
			}
		}
	}
}